import fs from 'fs';
import path from 'path';
import archiver from 'archiver';
import { v4 as uuidv4 } from 'uuid';

// 配置上传和临时目录
const UPLOAD_DIR = path.join(process.cwd(), 'frontend/uploads');
const TEMP_DIR = path.join(process.cwd(), 'frontend/temp');

// 确保目录存在
if (!fs.existsSync(UPLOAD_DIR)) {
  fs.mkdirSync(UPLOAD_DIR, { recursive: true });
}
if (!fs.existsSync(TEMP_DIR)) {
  fs.mkdirSync(TEMP_DIR, { recursive: true });
}

export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ 
      code: 405, 
      message: '方法不允许' 
    });
  }

  try {
    const { fileIds, format = 'zip', level = 'medium' } = req.body;

    if (!fileIds || !Array.isArray(fileIds) || fileIds.length === 0) {
      return res.status(400).json({
        code: 400,
        message: '未提供文件ID'
      });
    }

    // 检查所有文件是否存在
    const files = [];
    for (const fileId of fileIds) {
      // 查找匹配的文件
      const filesInDir = fs.readdirSync(UPLOAD_DIR);
      const matchingFile = filesInDir.find(f => f.startsWith(fileId));
      
      if (!matchingFile) {
        return res.status(404).json({
          code: 404,
          message: `文件ID为${fileId}的文件不存在`
        });
      }
      
      files.push({
        id: fileId,
        path: path.join(UPLOAD_DIR, matchingFile),
        name: matchingFile.substring(matchingFile.indexOf('_') + 1)
      });
    }

    // 创建压缩文件
    const compressId = uuidv4();
    const compressFileName = `${compressId}.${format}`;
    const compressFilePath = path.join(TEMP_DIR, compressFileName);
    const output = fs.createWriteStream(compressFilePath);
    const archive = archiver(format, {
      zlib: {
        level: level === 'low' ? 1 : level === 'medium' ? 5 : 9
      }
    });

    // 监听完成事件
    output.on('close', () => {
      const stats = fs.statSync(compressFilePath);
      
      res.status(200).json({
        code: 200,
        message: '文件压缩成功',
        data: {
          fileId: compressId,
          fileName: compressFileName,
          size: stats.size,
          downloadUrl: `/api/file/download/${compressId}`
        }
      });
    });

    // 监听错误事件
    archive.on('error', (err) => {
      console.error('文件压缩错误:', err);
      res.status(500).json({
        code: 500,
        message: '文件压缩失败'
      });
    });

    // 将输出流附加到归档
    archive.pipe(output);

    // 添加文件到归档
    for (const file of files) {
      archive.file(file.path, { name: file.name });
    }

    // 完成归档
    archive.finalize();
  } catch (error) {
    console.error('压缩文件异常:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
} 